/**
 * Created by Administrator on 2016/1/5.
 */
angular.module('bluetoothoptions.service',[])
  .service('blueToothOptionsService',['$http','$cordovaBluetoothSerial',function($http,$cordovaBluetoothSerial){
    var bluetoothdevices =[];

    //手机蓝牙的打开状态
    var bluetoothStatus = "unknow";

    //默认连接的蓝牙设备mac地址
    var defaultDevice = {};

    var idCardInfo = {}; //保存身份证读取出来的信息
    return {
      isEnabled: function () {
        return $cordovaBluetoothSerial.isEnabled().then(
          function () {bluetoothStatus = "已开";},
          function () {bluetoothStatus = "未开";}
        ); //then()返回的也是一个promise
      },
      getBleStatus:function(){
        return bluetoothStatus;
      },
      search:function(){
        bluetoothdevices = [];
        var promises = [];
        //alert('search bluetooth devices ...');
        //先列出已配对的蓝牙设备list
        var promise1 = $cordovaBluetoothSerial.list().then(
          function(devices){
            //alert('list:' + devices.length);
            devices.forEach(function(device){
              device.paired = 'true';
              bluetoothdevices.push(device);
            });
            //alert('step1:' + bluetoothdevices.length);
          },
          function(e){
            //console.log("Bluetooth search error occurs" + e);
          });
        promises.push(promise1);

        //再列出未配对的蓝牙设备list ,链式promise
        var promise2 = $cordovaBluetoothSerial.discoverUnpaired().then(
          function(devices){
            //alert('discoverUnpaired:' + devices.length);
            devices.forEach(function(device){
              device.paired = 'false';
              bluetoothdevices.push(device);
            });
            //alert('step2:' + bluetoothdevices.length);
          },
          function(e){
            //console.log("Bluetooth search error occurs" + e);
          });
        promises.push(promise2);

        //alert('b');
        return promises;
      },
      all: function() {
        return bluetoothdevices;
      },
      push: function(device){
        bluetoothdevices.push(device);
      },
      clear: function(devices){
        bluetoothdevices.clearAll();
      },
      connect: function(device) {
        //chats.splice(bluetoothdevices.indexOf(chat), 1);
      },
      getBleStatus:function(){
        return bluetoothStatus;
      },  setDefaultDevice: function(_name, _mac){
        //alert(_name + _mac);
        defaultDevice.name = _name;
        defaultDevice.mac = _mac;
        //本地存储
        //$cookieStore.put('defaultDevice', defaultDevice);

      },
      getDefaultDevice: function(){
        //从本地存储获取
        //return $cookieStore.get('defaultDevice').mac;
        return defaultDevice; //defaultDevice.mac;
      },
      //判断是否已经设置有默认的蓝牙读卡器
      hasDefaultDevice: function () {
        return defaultDevice.mac != null && defaultDevice.mac != "";
      }

    }
  }]);
